<template>
  <div class="comment-list">
    <!-- 评论输入框 -->
    <div class="comment-input-section" v-if="userStore.isLoggedIn">
      <div class="comment-input-wrapper">
        <el-avatar :src="getMediaUrl(userStore.userInfo?.avatar)" :size="32" class="user-avatar">
          {{ userStore.userInfo?.nickname?.charAt(0) }}
        </el-avatar>
        <div class="input-area">
          <el-input v-model="commentContent" type="textarea" :rows="3" placeholder="Write your comment..." maxlength="500"
            show-word-limit resize="none" />
          <div class="input-actions">
            <el-button type="primary" size="small" :loading="submitting" :disabled="!commentContent.trim()"
              @click="handleSubmitComment">
              Post a comment
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 未登录提示 -->
    <div class="login-prompt" v-else>
      <span>please</span>
      <el-button type="text" @click="$router.push('/login')">login</el-button>
      <span>Post a comment afterwards</span>
    </div>

    <!-- 评论列表 -->
    <div class="comments-section">
      <div class="comments-header">
        <span class="comment-count">{{ total }} A comment</span>
        <div class="sort-options">
          <el-radio-group v-model="sortType" size="small" @change="handleSortChange">
            <el-radio-button :label="2">latest</el-radio-button>
            <el-radio-button :label="3">hottest</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div class="comment-items" v-loading="loading">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-main">
            <el-avatar :src="getMediaUrl(comment.userAvatar)" :size="36" class="comment-avatar">
              {{ comment.userNickname?.charAt(0) }}
            </el-avatar>

            <div class="comment-content">
              <div class="comment-header">
                <span class="username">{{ comment.userNickname }}</span>
                <span class="comment-time">{{ formatCommentTime(comment.createdTime) }}</span>
              </div>

              <div class="comment-text">
                <span v-if="comment.replyToUserNickname" class="reply-to">
                  reply @{{ comment.replyToUserNickname }}：
                </span>
                {{ comment.content }}
              </div>

              <div class="comment-actions">
                <button class="action-btn like-btn" :class="{ active: comment.isLiked }"
                  @click="handleLikeComment(comment.id, comment.isLiked)">
                  <el-icon>
                    <CaretTop />
                  </el-icon>
                  <span>{{ comment.likeCount || 'like' }}</span>
                </button>

                <button class="action-btn reply-btn" @click="handleReplyComment(comment)">
                  <el-icon>
                    <ChatDotRound />
                  </el-icon>
                  <span>reply</span>
                </button>

                <button v-if="comment.userId === userStore.userInfo?.id" class="action-btn delete-btn"
                  @click="handleDeleteComment(comment.id)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  <span>Delete</span>
                </button>
              </div>
            </div>
          </div>

          <!-- 子评论 -->
          <div v-if="comment.children && comment.children.length > 0" class="sub-comments">
            <div v-for="subComment in comment.children" :key="subComment.id" class="sub-comment-item">
              <el-avatar :src="getMediaUrl(subComment.userAvatar)" :size="28" class="sub-comment-avatar">
                {{ subComment.userNickname?.charAt(0) }}
              </el-avatar>

              <div class="sub-comment-content">
                <div class="sub-comment-header">
                  <span class="username">{{ subComment.userNickname }}</span>
                  <span class="comment-time">{{ formatCommentTime(subComment.createdTime) }}</span>
                </div>

                <div class="sub-comment-text">
                  <span v-if="subComment.replyToUserNickname" class="reply-to">
                    reply @{{ subComment.replyToUserNickname }}：
                  </span>
                  {{ subComment.content }}
                </div>

                <div class="sub-comment-actions">
                  <button class="action-btn like-btn" :class="{ active: subComment.isLiked }"
                    @click="handleLikeComment(subComment.id, subComment.isLiked)">
                    <el-icon>
                      <CaretTop />
                    </el-icon>
                    <span>{{ subComment.likeCount || 'like' }}</span>
                  </button>

                  <button class="action-btn reply-btn" @click="handleReplyComment(subComment, comment)">
                    <el-icon>
                      <ChatDotRound />
                    </el-icon>
                    <span>reply</span>
                  </button>

                  <button v-if="subComment.userId === userStore.userInfo?.id" class="action-btn delete-btn"
                    @click="handleDeleteComment(subComment.id)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    <span>Delete</span>
                  </button>
                </div>
              </div>
            </div>

            <!-- 查看更多回复 -->
            <div v-if="comment.replyCount > 3" class="view-more-replies">
              <el-button type="text" size="small">
                View all {{ comment.replyCount }} Reply to the article
              </el-button>
            </div>
          </div>

          <!-- 回复输入框 -->
          <div v-if="replyingTo?.id === comment.id" class="reply-input-section">
            <div class="reply-input-wrapper">
              <el-avatar :src="getMediaUrl(userStore.userInfo?.avatar)" :size="28" class="user-avatar">
                {{ userStore.userInfo?.nickname?.charAt(0) }}
              </el-avatar>
              <div class="input-area">
                <el-input v-model="replyContent" type="textarea" :rows="2"
                  :placeholder="`reply @${replyingTo.userNickname}：`" maxlength="500" show-word-limit resize="none" />
                <div class="input-actions">
                  <el-button size="small" @click="cancelReply">Cancel</el-button>
                  <el-button type="primary" size="small" :loading="submitting" :disabled="!replyContent.trim()"
                    @click="handleSubmitReply">
                    reply
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more">
          <el-button type="text" :loading="loading" @click="loadMore">
            Load more comments
          </el-button>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && comments.length === 0" class="empty-state">
          <el-empty description="No comments, please post the first comment!" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CaretTop, ChatDotRound, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { createComment, deleteComment, getCommentList, toggleLikeComment } from '@/api/comment'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { getMediaUrl } from '@/utils/media'

// Props
const props = defineProps({
  targetId: {
    type: String,
    required: true
  },
  targetType: {
    type: Number,
    required: true
  }
})

// Store
const userStore = useUserStore()

// 响应式数据
const comments = ref([])
const total = ref(0)
const loading = ref(false)
const submitting = ref(false)
const commentContent = ref('')
const replyContent = ref('')
const replyingTo = ref(null)
const sortType = ref(2) // 1-时间正序，2-时间倒序，3-热度

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10
})

// 计算属性
const hasMore = computed(() => {
  return comments.value.length < total.value
})

// 生命周期
onMounted(() => {
  loadComments()
})

// 方法
const loadComments = async (isLoadMore = false) => {
  if (!isLoadMore) {
    loading.value = true
    pagination.pageNum = 1
  }

  try {
    const params = {
      targetId: props.targetId,
      targetType: props.targetType,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      sortType: sortType.value
    }

    const response = await getCommentList(params)
    if (response.code === 200) {
      const { data: list, total: totalCount } = response.data

      if (isLoadMore) {
        comments.value.push(...(list || []))
      } else {
        comments.value = list || []
      }

      total.value = totalCount
    } else {
      ElMessage.error(response.message || '获取评论失败')
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
  } finally {
    loading.value = false
  }
}

const handleSubmitComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  submitting.value = true
  try {
    const data = {
      targetId: props.targetId,
      targetType: props.targetType,
      content: commentContent.value.trim()
    }

    const response = await createComment(data)
    if (response.code === 200) {
      ElMessage.success('评论发表成功')
      commentContent.value = ''
      loadComments() // 重新加载评论列表
    } else {
      ElMessage.error(response.message || '评论发表失败')
    }
  } catch (error) {
    console.error('评论发表失败:', error)
    ElMessage.error('评论发表失败')
  } finally {
    submitting.value = false
  }
}

const handleReplyComment = (comment, parentComment = null) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  replyingTo.value = comment
  replyContent.value = ''
}

const handleSubmitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  submitting.value = true
  try {
    const data = {
      targetId: props.targetId,
      targetType: props.targetType,
      content: replyContent.value.trim(),
      parentId: replyingTo.value.parentId || replyingTo.value.id,
      replyToUserId: replyingTo.value.userId
    }

    const response = await createComment(data)
    if (response.code === 200) {
      ElMessage.success('回复发表成功')
      cancelReply()
      loadComments() // 重新加载评论列表
    } else {
      ElMessage.error(response.message || '回复发表失败')
    }
  } catch (error) {
    console.error('回复发表失败:', error)
    ElMessage.error('回复发表失败')
  } finally {
    submitting.value = false
  }
}

const cancelReply = () => {
  replyingTo.value = null
  replyContent.value = ''
}

const handleLikeComment = async (commentId, isLiked) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    const response = await toggleLikeComment(commentId)
    if (response.code === 200) {
      // 更新本地状态
      const updateComment = (commentList) => {
        commentList.forEach(comment => {
          if (comment.id === commentId) {
            comment.isLiked = !isLiked
            comment.likeCount += comment.isLiked ? 1 : -1
          }
          if (comment.children) {
            updateComment(comment.children)
          }
        })
      }
      updateComment(comments.value)
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleDeleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteComment(commentId)
    if (response.code === 200) {
      ElMessage.success('评论删除成功')
      loadComments() // 重新加载评论列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSortChange = () => {
  loadComments()
}

const loadMore = () => {
  pagination.pageNum++
  loadComments(true)
}

const formatCommentTime = (time) => {
  if (!time) return ''
  return formatDistanceToNow(new Date(time), {
    addSuffix: true,
    locale: zhCN
  })
}
</script>

<style scoped>
.comment-list {
  margin-top: 24px;
}

.comment-input-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.comment-input-wrapper {
  display: flex;
  gap: 12px;
}

.user-avatar {
  flex-shrink: 0;
}

.input-area {
  flex: 1;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.login-prompt {
  text-align: center;
  padding: 20px;
  color: #666;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 24px;
}

.comments-section {
  background: white;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 16px;
}

.comment-count {
  font-weight: 500;
  color: #333;
}

.comment-item {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-main {
  display: flex;
  gap: 12px;
}

.comment-avatar {
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
  min-width: 0;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.username {
  font-weight: 500;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  color: #333;
  line-height: 1.6;
  margin-bottom: 12px;
  word-break: break-word;
}

.reply-to {
  color: #1890ff;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border: none;
  background: none;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.like-btn.active {
  color: #1890ff;
}

.delete-btn:hover {
  color: #ff4d4f;
}

.sub-comments {
  margin-top: 16px;
  margin-left: 48px;
  padding-left: 16px;
  border-left: 2px solid #f0f0f0;
}

.sub-comment-item {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.sub-comment-avatar {
  flex-shrink: 0;
}

.sub-comment-content {
  flex: 1;
  min-width: 0;
}

.sub-comment-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.sub-comment-text {
  color: #333;
  line-height: 1.5;
  margin-bottom: 8px;
  word-break: break-word;
  font-size: 14px;
}

.sub-comment-actions {
  display: flex;
  gap: 12px;
}

.view-more-replies {
  margin-top: 8px;
}

.reply-input-section {
  margin-top: 12px;
  padding: 12px;
  background: #fafafa;
  border-radius: 6px;
}

.reply-input-wrapper {
  display: flex;
  gap: 8px;
}

.load-more {
  text-align: center;
  padding: 20px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}
</style>
